import time

from PyQt5.QtCore import QThread, pyqtSignal

import var


class LRUWorker(QThread):
    current_index_signal = pyqtSignal(int)
    current_pages_signal = pyqtSignal(list)

    output_signal = pyqtSignal(str)

    def __init__(self, mission, num_frames):
        super(LRUWorker, self).__init__()
        self.page_requests = mission.copy()
        self.num_frames = num_frames
        self.current_index = 0

    def updateIndex(self):
        self.current_index_signal.emit(self.current_index)

    def updatePages(self, input_list):
        self.current_pages_signal.emit(input_list)

    def run(self):
        out_str = ""
        print("receive run")
        page_queue = []
        page_faults = 0
        page_count = []
        g_page_requests = self.page_requests
        for page in g_page_requests:  # 依次请求页面
            self.current_index += 1
            self.updateIndex()
            time.sleep(var.time_split)
            try:
                self.updatePages(page_queue)

                print("页面队列的计时器", end='')
                print(page_count)

                if page in page_queue:
                    t = page_queue.index(page)
                    page_count[t] = 0

                elif len(page_queue) < self.num_frames:
                    page_queue.append(page)
                    page_count.append(0)
                else:
                    t = page_count.index(max(page_count))
                    page_count[t] = 0
                    page_queue[t] = page
                    page_faults += 1
                    out_str += f"下标 {self.current_index - 1} 发生页面置换\n"
                    self.output_signal.emit(out_str)

            finally:
                self.page_requests = self.page_requests[1:]
                page_count = [x + 1 for x in page_count]

        # page_faults 页面置换次数
        out_str += f"运行结束\n总页面置换次数 {page_faults}"
        self.output_signal.emit(out_str)
        print("finish")
